<?php

namespace App\Http\Controllers\Home;

use App\Models\Ads;
use App\Models\Goods;
use App\Models\Slider;
use App\Models\TypesAds;
use App\Types;
use Illuminate\Http\Request;

//使用类
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

//前台首页控制器
class IndexController extends Controller
{
    //分类数据处理
    public function checkTypeData($data,$pid=0){

        //新建数组
        $newArr=array();
        //获取数据
        foreach($data as $key=>$value){

            if($value->pid == $pid){
                $newArr[$value->id]=$value;

                $newArr[$value->id]['zi']=$this->checkTypeData($data,$value->id);//[][] 都是键 (一维)(二维)   types数组 zi字段
            }

        }

        //返回数据
        return $newArr;

    }


    //前台首页
	public function index(){
		//加载页面

        //查询轮播图 Cache::has('key')
        if(Cache::has('slider')){//获取到缓存
            $slider = Cache::get('slider');
        }else{
            $slider = Slider::orderBy("order","desc")->get();
            Cache::put("slider",$slider,1440);
        }

        //dd($slider);

        //查询广告
        if($ads=Cache::get('ads')){

        }else{
            $ads= Ads::orderBy("sort","desc")->get();
            Cache::put("ads",$ads,1440);
        }

        //处理左侧数据分类
        $types=Types::get();


        //递归处理数据
       $type =  $this->checkTypeData($types);  //接收数据
        //dd($type);

        //处理右侧广告
        foreach($type as $key => $value){

            $value->rightAds = TypesAds::where([["cid","=",$value->id],['type','=',0]])->limit(2)->get(); //types数组 rightAds字段
            $value->leftAds = TypesAds::where([["cid","=",$value->id],['type','=',1]])->first();//一条  types数组 leftAds字段

        }

        //处理楼层的商品
      //  echo "<pre>";
        //遍历一级分类
        foreach($type as $key => $value){
            //print_r($value);
            //新建数组
            $newArr=[];

            //遍历二级分类
            foreach($value->zi as $two){

                //遍历三级分类
                foreach($two->zi as $three){
                    $newArr[]=$three->id;
                }
            }
            //print_r($newArr);//读取到对应三级分类
            $value->goods=Goods::whereIn("cid",$newArr)->limit(8)->get(); //types数组 goods字段
        }
       // exit;


//dd($type);
        //明星单品 (未设置明星单品字段)
        $goods = Goods::limit(6)->orderBy("id","desc")->get();
//dd($goods);

        //格式化数据
        $data= array(
            "slider"=>$slider,
            "ads"=>$ads,
            "type"=>$type,
            "goods"=>$goods,
        );

        return view("home.index")->with($data);
	}
	
}
